package com.zivwu.library.dao.net;

import com.zivwu.library.widget.progress.ProgressListener;

import java.io.IOException;

import io.reactivex.annotations.Nullable;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;


public class ProgressResponseBody extends ResponseBody {
    ResponseBody body;
    ProgressListener.onProgress listener;
    private BufferedSource buffer;

    public ProgressResponseBody(ResponseBody body, ProgressListener.onProgress listener) {
        this.body = body;
        this.listener = listener;
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return body.contentType();
    }

    @Override
    public long contentLength() {
        return body.contentLength();
    }

    @Override
    public BufferedSource source() {
        if (buffer == null)
            buffer = Okio.buffer(source(body.source()));
        return buffer;
    }


    private Source source(Source source) {
        return new ForwardingSource(source) {
            //当前读取字节数
            long totalBytesRead = 0L;

            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                //增加当前读取的字节数，如果读取完成了bytesRead会返回-1
                totalBytesRead += bytesRead != -1 ? bytesRead : 0;
                //回调，如果contentLength()不知道长度，会返回-1
                int progress = (int) (totalBytesRead / body.contentLength());
                listener.onProgress(progress);
                return bytesRead;
            }
        };
    }
}
